#!/usr/local/bin/perl -w
#use strict;
use FindBin qw($RealBin);
use lib "$RealBin/../perl_lib";
use Gtk2 '-init';
use Glib qw/TRUE FALSE/;
use Gtk2::Gdk::Keysyms;
use Top ':subs';
use IO::Socket;
use Data::Dump 'dump';
use Gen::Base;
use Error qw(:try);

#@ARGV = ('127.0.0.1:59905', 164, 10, 1, 'admin');

use vars qw/%ARGS $MW $SCRIPT_RETURN $USER_NAME $USER_FULLNAME $USER_ID $GEN $LANG $JOB $STEP $JOB_ID $RUN_MODE $PAR $RUN_DATA $GEN_TYPE $IKM/;
$APP = {};
unless (scalar (@ARGV) && $ARGV[0] ne "") {
	print("\nError: No Args passed to  prog. Exiting...\n");
    exit 0;
}
 
eval
{
	$ARGS{socket} = shift @ARGV;
	$ARGS{job_id} = shift @ARGV;
	$ARGS{process_id} = shift @ARGV;
	$ARGS{script_id} = shift @ARGV;
	$ARGS{user} = shift @ARGV;
	$ARGS{data} = shift @ARGV;
	
	$SIG{INT} = $SIG{TERM} = $SIG{HUP} = \&tl_end;
	
	$APP->{THEME} = {
		top_headbox_bgcolor => '#1D690C',
		top_headbox_fgcolor => 'white',
		top_headbox_font => '12',
		top_formpanel_label =>{
			fgcolor => '#1D690C',
		},
		top_formpanel_units => {
			fgcolor => 'navyblue',
		},
		top_formpanel_remark=>{
			fgcolor => 'grey',
		},
		top_formpanel_title=>{
			title_bgcolor => '#639805',
			title_fgcolor => 'white',
		},
		top_formpanel_bgcolor => '#FAF8F2', 
		top_formpanel_paper_color => '#FCFCFC', 

		top_treeview => {
			'text_active'=>'white',
			'text_prelight'=>'white',
			'text_selected'=>'white',
			'base_selected'=>'#76AB43',
			'base_prelight'=>'#76AB43',
			'base_active'=>'#76AB43',
		},
		top_treeview_insensitive => {
			'text_active'=>'red',
			'text_prelight'=>'red',
			'text_selected'=>'red',
		},
		top_blue_text => {
			fg_normal => 'navyblue',
			fg_insensitive => 'navyblue',
			font => 'bold',
		}
	};
	
	Top->load_language('chinese_simple');
	Top->load_stock('gtk_script_driver');
	
	my $init_module_list = [
		'TL_Gtk2_HeadBox',
		'TL_Gtk2_Panel',
		'TL_Gtk2_TreeView',
		'TL_Gtk2_BorderPanel',
		'TL_Gtk2_CalendarEntry',
		'TL_Gtk2_CheckBox',
		'TL_Gtk2_ComboBox',
		'TL_Gtk2_ComboBoxEntry',
		'TL_Gtk2_DateEntry',
		'TL_Gtk2_DateTimeEntry',
		'TL_Gtk2_FormPanel',
		'TL_Gtk2_HBoxPanel',
		'TL_Gtk2_HyperTextToolbar',
		'TL_Gtk2_HyperTextView',
		'TL_Gtk2_ImgLabelBox',
		'TL_Gtk2_IntegerEntry',
		'TL_Gtk2_JobSelectorEntry',
		'TL_Gtk2_LayerSelectorEntry',
		'TL_Gtk2_MultipleEntry',
		'TL_Gtk2_NaviTree',
		'TL_Gtk2_NumberEntry',
		'TL_Gtk2_NumberUnitsEntry',
		'TL_Gtk2_PagePanel',
		'TL_Gtk2_PageTool',
		'TL_Gtk2_Photo',
		'TL_Gtk2_PopupWindow',
		'TL_Gtk2_RadioBox',
		'TL_Gtk2_RangeEntry',
		'TL_Gtk2_SearchTool',
		'TL_Gtk2_StepSelectorEntry',
		'TL_Gtk2_TableFormPanel',
		'TL_Gtk2_TablePanel',
		'TL_Gtk2_TimeEntry',
		'TL_Gtk2_TitleExpander',
		'TL_Gtk2_ToleranceEntry',
		'TL_Gtk2_UIFactory',
		'TL_Gtk2_UIManager',
		'TL_Gtk2_VBoxPanel',
	];
	
	foreach my $module (@$init_module_list)
	{
		use_module($module);
	}
	
	use_module('TOP_GUI');
	use_module('TOP_IKM');
	$IKM = TOP::IKM->new;
	$IKM->set_socket_server(split(':', $ARGS{socket}));
	
	#获取配置文件
	my $cfg_file = $RealBin.'/../configure/topcam.cfg';
	$APP->{CONFIG} = do($cfg_file);
	
	$APP->{WGT}{MW} = $APP->{WGT}{MW_LOADING} = $MW = Gtk2::Window->new('popup');
	$APP->{WGT}{MW}->move(0,0);
	my $ebx = Gtk2::EventBox->new();
	$ebx->set_above_child(1);
	$ebx->signal_connect(
		'button-press-event' => sub{
			my ($widget,$event) = @_;
			if ($event->button == 1){
				if ($event->type eq 'button-press'){
					($ebx->{REF_X},$ebx->{REF_Y})  = ($event->x,$event->y);
					$ebx->{START_MOVE} = 1;
				}
				elsif($event->type eq '2button-press'){
					$APP->{WGT}{MW_LOADING}->hide();
					hide_loading();
				}
			}
			return 0;
		}
	);
	$ebx->signal_connect(
		'button-release-event' => sub{
			my ($widget,$event) = @_;
			$ebx->{START_MOVE} = 0;
			return 0;
		}
	);
	$ebx->signal_connect(
		'motion-notify-event' => sub{
			my ($widget,$event) = @_;
			if ($ebx->{START_MOVE}){
				my ($x,$y)  = $event->get_root_coords();
				$APP->{WGT}{MW_LOADING}->move($x-$ebx->{REF_X}, $y-$ebx->{REF_Y}) ;
			}
			return 0;
		}
	);
	
	$APP->{WGT}{PROGRESS} = Gtk2::ProgressBar->new();
	$APP->{WGT}{PROGRESS}->set_property(name=>'top-main-progress',pulse_step=>0.05);
	$APP->{WGT}{PROGRESS}->modify_fg('normal',Gtk2::Gdk::Color->parse('blue'));
	$APP->{WGT}{PROGRESS}->modify_font(Gtk2::Pango::FontDescription->from_string('12'));
	$ebx->add($APP->{WGT}{PROGRESS});
	$APP->{WGT}{MW_LOADING}->add($ebx); 
	
	$APP->{GUI} = $GUI = TOP::GUI->new;
	
	#获取步骤参数
	$PAR = {};
	my $process = $IKM->get_process_by_id($ARGS{process_id});
	
	if ($process->{script_parameter})
	{
		my $json = new JSON;
		my $par = $json->decode($process->{script_parameter});
		if (ref($par) eq 'HASH')
		{
			$PAR = $par;
		}
	}
	#print dump($PAR),"\n";
	use_module("TOP_GEN");
	$GEN = TOP::GEN->new(-gentype=>'genesis');
	$USER_NAME = $ARGS{user};
	$USER_NAME = $GEN->getUserName() unless $USER_NAME;
	($USER_NAME,$USER_FULLNAME,$USER_ID) = split(':', $USER_NAME);
	$JOB = $ENV{'JOB'};
	$STEP = $ENV{'STEP'};
	$JOB_ID = $ARGS{job_id};
	$JOB = lc($IKM->get_job_name($JOB_ID)) if $JOB_ID;
	$SCRIPT_RETURN = _do_script(%{$IKM->get_script_by_id($ARGS{script_id})});

};
print $@,"\n" if $@;
END {   
	tl_end();
}


sub doScript
{
	my $script_name = shift;
	return _do_script(%{$IKM->get_script_by_name($script_name)});
}



sub _do_script
{
	my %par = @_;
	my $return;
	##
	if ($APP->{CONFIG}{'debug_mode'} and $APP->{CONFIG}{'debug_mode'} =~ /1|yes/i
		and (-f $APP->{CONFIG}{'script_path'}.'/'.$par{name}.'.pl'))
	{
		$return = eval(Top->file2str(-file=>$APP->{CONFIG}{'script_path'}.'/'.$par{name}.'.pl'));
	}
	else
	{
		if ($par{content})
		{
			if ($par{encrypt} == 2)
			{
				$return = eval(main::dc_tl2($par{content}));
			}
			elsif ($par{encrypt} == 1)
			{
				$return = eval(main::dc_tl1($par{content}));
			}
			else
			{
				$return = eval($par{content});
			}
		}
	
	}
	print @$ , "\n" if @$;
	return $return;
}

sub _use_module{
	my $module = shift;
	return if ($APP->{loaded_module}{$module} );
	my $file = $RealBin.'/../top_lib/'.$module;
	if (-f $file.'.pm')
	{
		do($file.'.pm');
	}
	elsif (-f $file. '.TL2')
	{
		eval(dc_tl2(file2str($file.'.TL2')));
	}
	print $@,"\n" if $@;
	$APP->{loaded_module}{$module} = 1;
}


sub tl_end
{
	my $status;
    $SCRIPT_RETURN = 'Error' unless $SCRIPT_RETURN;
	if($SCRIPT_RETURN =~ /^done/i){
		$status='Done';
	}
	elsif($SCRIPT_RETURN =~ /^cancel/i){
		$status='Cancel';
	}
	elsif($SCRIPT_RETURN =~ /^warning/i){
		$status='Warning';
	}
	elsif($SCRIPT_RETURN =~ /^finish/i){
		$status = 'Finish';
	}
	elsif($SCRIPT_RETURN =~ /^critical/i){
		$status = 'Critical'
	}
	elsif($SCRIPT_RETURN =~ /^new/i){
		$status = 'New'
	}
	else{
		$status = 'Error';
	}

	if ($ARGS{socket}){

		$IKM->update_job_workflow_log(job_id=>$ARGS{job_id},
									  process_id=>$ARGS{process_id},
									  end_time=>now(),
									  user_name=>$USER_FULLNAME,
									  user_id=>$USER_ID,
									  status=>$status,
									  notes=>($ARGS{job_id} > 0) ? "$USER_FULLNAME $status script (jobname=$JOB,jobid=$ARGS{job_id})" : '') if $ARGS{job_id};
									  
		$IKM->script_end($ARGS{job_id}, $ARGS{process_id});
	}

}


sub now {
    my $self = shift;
    my ($sec,$min,$hour,$day,$mon,$year,$weekday,$yearday,$isdst)=localtime;
    return sprintf('%4d-%02d-%02d %02d:%02d:%02d',$year+1900,++$mon,$day,$hour,$min,$sec);
}

#Get date
sub today {
    my $self = shift;
    my ($sec,$min,$hour,$day,$mon,$year,$weekday,$yearday,$isdst)=localtime;
    return sprintf('%4d-%02d-%02d',$year+1900,++$mon,$day);
}

#get time
sub time {
    my $self = shift;
    my ($sec,$min,$hour,$day,$mon,$year,$weekday,$yearday,$isdst)=localtime;
    return sprintf('%02d:%02d:%02d',$hour,$min,$sec);
}

